package com.bmd.backgroundmanger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmd.backgroundmanger.entity.UserFavorite;
import com.bmd.backgroundmanger.mapper.UserFavoriteMapper;
import com.bmd.backgroundmanger.service.IUserFavoriteService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户收藏Service实现类
 */
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements IUserFavoriteService {

    @Override
    public boolean addFavorite(Integer userId, Integer questionId) {
        // 检查是否已收藏
        if (isFavorite(userId, questionId)) {
            return false;
        }
        
        UserFavorite favorite = new UserFavorite();
        favorite.setUserId(userId);
        favorite.setQuestionId(questionId);
        favorite.setCreateTime(LocalDateTime.now());
        
        return save(favorite);
    }

    @Override
    public boolean removeFavorite(Integer userId, Integer questionId) {
        LambdaQueryWrapper<UserFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFavorite::getUserId, userId)
                .eq(UserFavorite::getQuestionId, questionId);
        
        return remove(wrapper);
    }

    @Override
    public List<UserFavorite> getUserFavorites(Integer userId) {
        return baseMapper.selectFavoritesByUserId(userId);
    }

    @Override
    public boolean isFavorite(Integer userId, Integer questionId) {
        Integer count = baseMapper.checkFavoriteExists(userId, questionId);
        return count > 0;
    }
} 